using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;

public class CrossPromotionHandler : MonoBehaviour
{
	[Serializable]
	private struct CrossPromotionGetData
	{
		public string udid;

		public string os;

		public string bundleId;

		public int sessionId;

		public string advertisingID;

		public CrossPromotionGetData(string udid, string advertisingID, string os, string bundleId, int sessionId)
		{
			this.udid = udid;
			this.os = os;
			this.bundleId = bundleId;
			this.sessionId = sessionId;
			this.advertisingID = advertisingID;
		}
	}

	[Serializable]
	private struct CrossPromotionPostData
	{
		public string udid;

		public string os;

		public string bundleId;

		public int sessionId;

		public string type;

		public string appBundleId;

		public string advertisingID;

		public CrossPromotionPostData(string udid, string advertisingID, string os, string bundleId, int sessionId, string type, string appBundleId)
		{
			this.udid = udid;
			this.os = os;
			this.bundleId = bundleId;
			this.sessionId = sessionId;
			this.type = type;
			this.appBundleId = appBundleId;
			this.advertisingID = advertisingID;
		}
	}

	[Serializable]
	private struct CrossPromotionServiceResult
	{
		public string imageUrl;

		public string appName;

		public string appUrl;

		public string appBundleId;

		public int version;
	}

	[Serializable]
	private struct Data
	{
		public string data;
	}

	public delegate void CrossPromotionEvent(CrossPromotionResult result);

	private const string crossPromotionURL = "http://54.149.211.245";

	private static Dictionary<string, string> headers = new Dictionary<string, string>();

	private static bool crosspromoLoaded;

	private static CrossPromotionResult result;

	private static string advertisingId = null;

	public static bool CrosspromoLoaded
	{
		get
		{
			return crosspromoLoaded;
		}
	}

	public static CrossPromotionResult Result
	{
		get
		{
			return result;
		}
	}

	public static event CrossPromotionEvent OnCrossPromotionSuccess;

	public void CrossPromotionSuccess(CrossPromotionResult result)
	{
		if (CrossPromotionHandler.OnCrossPromotionSuccess != null)
		{
			CrossPromotionHandler.OnCrossPromotionSuccess(result);
		}
	}

	private void Awake()
	{
		advertisingId = null;
		headers.Add("Content-Type", "application/json");
		Application.RequestAdvertisingIdentifierAsync(HandleAdvertisingIdentifierCallback);
	}

	private void HandleAdvertisingIdentifierCallback(string advertisingID, bool trackingEnabled, string errorMsg)
	{
		if (advertisingId == null)
		{
			advertisingId = string.Empty;
		}
		advertisingId = advertisingID;
	}

	private void OnEnable()
	{
		Utils.OnSessionCountChanged += Handle_OnSessionCountChanged;
	}

	private void OnDisable()
	{
		Utils.OnSessionCountChanged -= Handle_OnSessionCountChanged;
	}

	private void Handle_OnSessionCountChanged()
	{
		StopAllCoroutines();
		StartCoroutine(DataFromServer(5f));
	}

	private IEnumerator DataFromServer(float timeOut)
	{
		if (advertisingId == null)
		{
			yield return new WaitUntil(() => advertisingId != null);
		}
		crosspromoLoaded = false;
		result = null;
		string data = JsonUtility.ToJson(new CrossPromotionGetData(SystemInfo.deviceUniqueIdentifier, advertisingId, Application.platform.ToString(), Application.identifier, Utils.instance.SessionCount));
		string dataString = "{\"data\":\"" + Security.EncryptStringAES(data) + "\"}";
		byte[] dataBytes = Encoding.UTF8.GetBytes(dataString);
		WWW www = new WWW("http://54.149.211.245/api/ads", dataBytes, headers);
		float time = 0f;
		bool timedOut = false;
		while (!www.isDone)
		{
			time += Time.deltaTime;
			yield return null;
			if (time > timeOut)
			{
				timedOut = true;
				break;
			}
		}
		if (timedOut)
		{
			www.Dispose();
		}
		else
		{
			if (!string.IsNullOrEmpty(www.error) || string.IsNullOrEmpty(www.text))
			{
				yield break;
			}
			CrossPromotionServiceResult cpsr = JsonUtility.FromJson<CrossPromotionServiceResult>(Security.DecryptStringAES(JsonUtility.FromJson<Data>(www.text).data));
			yield return StartCoroutine(DownloadImageOrLoadFromCache(cpsr.imageUrl, cpsr.appBundleId, cpsr.version, delegate(Texture2D texture)
			{
				if (texture != null)
				{
					crosspromoLoaded = true;
					result = new CrossPromotionResult(cpsr.appName, cpsr.appUrl, cpsr.appBundleId, texture);
					CrossPromotionSuccess(new CrossPromotionResult(cpsr.appName, cpsr.appUrl, cpsr.appBundleId, texture));
				}
			}));
		}
	}

	public static IEnumerator DownloadImageOrLoadFromCache(string url, string bundleId, int version, Action<Texture2D> callback)
	{
		Texture2D texture = new Texture2D(2, 2);
		string filename = bundleId + "-" + Path.GetFileNameWithoutExtension(url) + "-" + version;
		if (PlayerPrefs.HasKey(filename))
		{
			texture.LoadImage(Convert.FromBase64String(PlayerPrefs.GetString(filename)));
			while (texture == null)
			{
				yield return 0;
			}
			callback(texture);
			yield break;
		}
		WWW www = new WWW(url);
		yield return www;
		if (string.IsNullOrEmpty(www.error) && www.texture != null)
		{
			texture = www.texture;
			PlayerPrefs.SetString(filename, Convert.ToBase64String(texture.EncodeToPNG()));
			callback(texture);
		}
		else
		{
			Debug.Log(www.error);
			callback(null);
		}
	}

	public static IEnumerator SendClickToServer(string url, string appBundleId, float timeOut)
	{
		string data = JsonUtility.ToJson(new CrossPromotionPostData(SystemInfo.deviceUniqueIdentifier, advertisingId, Application.platform.ToString(), Application.identifier, Utils.instance.SessionCount, "click", appBundleId));
		string dataString = "{\"data\":\"" + Security.EncryptStringAES(data) + "\"}";
		byte[] dataBytes = Encoding.UTF8.GetBytes(dataString);
		WWW www = new WWW("http://54.149.211.245/api/action", dataBytes, headers);
		float time = 0f;
		bool timedOut = false;
		while (!www.isDone)
		{
			time += Time.deltaTime;
			yield return null;
			if (time > timeOut)
			{
				timedOut = true;
				break;
			}
		}
		Application.OpenURL(url);
	}
}
